<?php
/**
 * Created by PhpStorm.
 * User: jin
 * Date: 2015/8/24
 * Time: 9:32
 */

namespace Home\Model;
use Think\Exception;
use Think\Model;

class HospitalModel extends Model
{
    private $hos_id = 0;
    static private $tName = 'hospital_hospital';
    /**
     * 添加医院
     * @param array $hospitalInfo
     * @return int|mixed
     */
    public function addHospital($hospitalInfo = null)
    {
        try
        {
            $data = array(
                'hos_name'=>I('post.hos_name'),
                'hos_tel_1'=>I('post.hos_tel_1'),
                'hos_tel_2'=>I('post.hos_tel_2'),
                'hos_introduction'=>I('post.hos_introduction'),
                'hos_detailed_address'=>I('post.hos_detailed_address'),
                'hos_sort'=>I('post.hos_sort'),
                'pro_id'=>I('post.province'),
                'city_id'=>I('post.city'),
                'lev_id'=>I('post.level'),
                'hos_route'=>I('post.hos_route'),
                'hos_description'=>I('post.hos_description')
            );
            //插入医院主表数据
            $this->hos_id = $this->add($data);
            if(!$this->hos_id)
            {
                throw new \Exception(1);
            }

            $imageUploadInfo = \Home\Model\Upload::uploadImage('hos_image','hospital'.$this->hos_id);

           // dump($imageUploadInfo);die();
            if(false === $imageUploadInfo['sta'])
            {
                throw new \Exception(2);
            }
            //插入医院图片路径
            $updateHospital = M()->table(self::$tName)->where(array('hos_id'=>$this->hos_id))->save(array('hos_image'=>$imageUploadInfo['fileName']));
            if(false === $updateHospital)
            {
                throw new \Exception(3);
            }
            //插入医生信息
            $doctorId = \Home\Model\DoctorModel::addDoctors(explode('|',I('post.hos_docter')));
            if(count($doctorId) <= 0)
            {
                throw new \Exception(4);
            }
            //插入医院医生关联
            $hosDocNum = \Home\Model\HosDocModel::addHosDoc($this->hos_id,$doctorId);
            if(count($doctorId) > $hosDocNum)
            {
                throw new \Exception(5);
            }
            return array('sta'=>$this->hos_id);
        }
        catch(\Exception $e)
        {
            $errorMessage = '';
            switch($e->getMessage())
            {
                case 1:
                    $errorMessage = '插入失败';
                    break;
                case 2:
                    $this->delHospital($this->hos_id);
                    $errorMessage = '图片上传失败';
                    break;
                case 3:
                    $this->delHospital($this->hos_id);
                    file_exists($imageUploadInfo['fileName']) ? unlink($imageUploadInfo['fileName']) : 0;
                    $errorMessage = '更新图片信息失败';
                    break;
                case 4:
                    $this->delHospital($this->hos_id);
                    file_exists($imageUploadInfo['fileName']) ? unlink($imageUploadInfo['fileName']) : 0;
                    $errorMessage = '插入医生信息失败';
                    break;
                case 5:
                    $this->delHospital($this->hos_id);
                    file_exists($imageUploadInfo['fileName']) ? unlink($imageUploadInfo['fileName']) : 0;
                    //删除医生
                    \Home\Model\DoctorModel::delDoctorsForDocId($doctorId);
                    //删除医院医生关联
                    \Home\Model\HosDocModel::delHosDocForHosId($this->hos_id);
                    $errorMessage = '插入医院医生关联信息失败';
                    break;
            }
            return array('sta'=>false,'errorMessage'=>$errorMessage);
        }
    }

    /**
     *  根据Id删除医院
     * @param int $hospitalId
     * @return mixed
     */
    public function delHospital($hospitalId)
    {
        return $this->delete(array('hos_id'=>$hospitalId));
    }

    /**
     * 获取医院列表
     */
    public function getHospitalListByCityId($cityId)
    {
        $sql = 'SELECT * from hospital_hospital WHERE city_id = '.$cityId.' ORDER BY hos_id ASC';
        return $this->query($sql);
    }

    public function getHospitalListByProId($proId)
    {
        $sql = 'SELECT * from hospital_hospital WHERE pro_id = '.$proId.' ORDER BY hos_id ASC';
        return $this->query($sql);
    }

    static public function getHospitalList($proId,$cityId,$levelId)
    {
        $sql = <<<sql
SELECT a.hos_id,a.hos_name,a.hos_introduction,a.hos_image,a.hos_url,a.hos_detailed_address,b.lev_name,count(c
.score_id) as score_count,avg(c.score_score) as score 
FROM 
hospital_hospital AS a 
JOIN 
hospital_level as b 
ON (a.lev_id = b.lev_id) 
left join 
hospital_hospital_score as c 
on 
a.hos_id = c.hospital_id 
sql;
        if($proId || $cityId || $levelId)
        {
            $sql .= '  where';
            $whereArr = array();
            $proId > 0 ? array_push($whereArr," a.pro_id = {$proId}") : 0;
            $cityId > 0 ? array_push($whereArr," a.city_id = {$cityId}") : 0;
            $levelId > 0 ? array_push($whereArr," a.lev_id = {$levelId}") : 0;
            $sql .= implode(' and ',$whereArr);
        }
        $sql .= ' group by a.hos_id ORDER BY hos_sort ASC';
        return M()->query($sql);
    }

    /**
     * @param array $where
     * @param bool $data
     */
    static public function updateHospitalForId($hosId,$data)
    {
//        self::checkData($data);
        try
        {
            //判断是否存在上传文件，有则上传
            if($_FILES['hos_image']['name'])
            {

                $imageUploadInfo = \Home\Model\Upload::uploadImage('hos_image','hospital'.$hosId);
                if(false === $imageUploadInfo['sta'])
                {
                    throw new \Exception(1);
                }
                //插入医院图片路径
//                    file_exists($data['image_check']) ? unlink($data['image_check']) : 0;
                $data['hos_image'] = $imageUploadInfo['fileName'];

            }
            //插入医生主表数据
            if(!empty($data['hos_docter']))
            {
                $sql = <<<str
SELECT b.doc_id,b.doc_name
FROM
hospital_hospital_doctor AS a
LEFT JOIN
hospital_doctor AS b
ON
a.doc_id = b.doc_id
WHERE a.hos_id = {$hosId}
str;
                $doctorInfo = M()->query($sql);

                $addDoctorTemp = explode('|',$data['hos_docter']);
                $addDoctor = $addDoctorTemp;
                $delDoctorId = array();
                //去除需要删除和入库的医生信息
                foreach($doctorInfo as $doctorInfoKey => $doctorInfoValue)
                {
                    $flag = 1;
                    foreach($addDoctorTemp as $addDoctorTempKey =>$addDoctorTempValue)
                    {
                        if($doctorInfoValue['doc_name'] == $addDoctorTempValue)
                        {
                            //把已经在数据库存在的从等待入库的信息中去掉
                            while(array_search($addDoctorTempValue,$addDoctor) !== false)
                            {
                                array_splice($addDoctor,array_search($addDoctorTempValue,$addDoctor),1);
                            }
                            $flag = 0;
                        }
                    }
                    if($flag)
                    {
                        $delDoctorId[] = $doctorInfoValue['doc_id'];
                    }
                }

                //新加入的医生和医院关联起来
                if($addDoctor)
                {

                    $doctorIdArr = \Home\Model\DoctorModel::addDoctors($addDoctor);
                    if(!$doctorIdArr)
                    {
                        throw new \Exception(2);
                    }
                    if(false === \Home\Model\HosDocModel::addHosDoc($hosId,$doctorIdArr))
                    {
                        throw new \Exception(3);
                    }
                }
                //删除不需要的医生相关数据
                if($delDoctorId)
                {
                    //删除不需要的医生信息
                    \Home\Model\DoctorModel::delDoctorsForDocId($delDoctorId);
                    //删除不需要的关联信息
                    \Home\Model\HosDocModel::delHosDocForDocId($delDoctorId);
                }

            }
            if(isset($data['hos_docter'])) unset($data['hos_docter']);
            if(isset($data['image_check'])) unset($data['image_check']);
            //更新医生消息
            M()->table(self::$tName)->where(array('hos_id'=>$hosId))->save($data);
            return array('sta'=>true);

        }
        catch(\Exception $e)
        {
            $errorMessage = '';
            switch($e->getMessage())
            {
                case 1:
                    $errorMessage = '图片上传失败';
                    break;
                case 3:
                    if(isset($imageUploadInfo['fileName'])) file_exists($imageUploadInfo['fileName']) ? unlink($imageUploadInfo['fileName']) : 0;
                    $errorMessage = '插入医院信息失败';
                    break;
                case 3:
                    if(isset($imageUploadInfo['fileName'])) file_exists($imageUploadInfo['fileName']) ? unlink($imageUploadInfo['fileName']) : 0;
                    if($addDoctor) \Home\Model\DoctorModel::delDoctorsForDocId($addDoctor);
                    $errorMessage = '插入医院医生关联信息失败';
                    break;
            }
            return array('sta'=>false,'errorMessage'=>$errorMessage);
        }
    }

    /**
     * @param int $hosId
     * @return bool|mixed
     */
    static public function getHospitalDetail($hosId)
    {
        $sql = <<<sql
select a.*,count(g.score_id) as score_count,avg(g.score_score) as score 
from 
(SELECT a.*,b.pro_name,c.city_name,d.lev_name,e.doc_id,f.doc_name,GROUP_CONCAT(f.doc_name) AS doctor_name
FROM
hospital_hospital AS a
LEFT JOIN
hospital_province AS b
ON
a.pro_id = b.pro_id
LEFT JOIN
hospital_city AS c
ON
a.city_id = c.city_id
LEFT JOIN
hospital_level AS d
ON
a.lev_id = d.lev_id
LEFT JOIN
hospital_hospital_doctor AS e
ON
a.hos_id = e.hos_id
LEFT JOIN
hospital_doctor AS f
ON
e.doc_id = f.doc_id
WHERE a.hos_id = {$hosId} ) as a 
left join 
hospital_hospital_score as g
on 
a.hos_id = g.hospital_id 
group by a.hos_id order by null 
sql;
        $hospitalDetail = M()->query($sql);
        $hospitalDetail = $hospitalDetail ? $hospitalDetail[0] :false;
        return $hospitalDetail;
    }


    /**
     * @param array $data
     * @return array $result
     */
    static function checkData($data)
    {
        try
        {
            if(empty($data['hos_name'])) throw new \Exception('1');
            if(empty($data['hos_tel_1'])) throw new \Exception('2');
            if(empty($data['hos_tel_2'])) throw new \Exception('3');
            if(empty($data['hos_introduction'])) throw new \Exception('4');
            if(empty($data['hos_detailed_address'])) throw new \Exception('5');
            if(empty($data['pro_id'])) throw new \Exception('6');
            if(empty($data['city_id'])) throw new \Exception('7');
            if(empty($data['lev_id'])) throw new \Exception('8');
            if(empty($data['hos_route'])) throw new \Exception('9');
            if(empty($data['hos_description'])) throw new \Exception('10');
            $res = array('sta'=>true);
        }
        catch(\Exception $e)
        {
            switch($e->getMessage())
            {
                case 1:
                    $errorMessage = '名字不能为空';
                    break;
                case 2:
                    $errorMessage = '电话不能为空';
                    break;
                case 3:
                    $errorMessage = '电话不能为空';
                    break;
                case 4:
                    $errorMessage = '简介不能为空';
                    break;
                case 5:
                    $errorMessage = '详细地址不能为空';
                    break;
                case 6:
                    $errorMessage = '所属省市不能为空';
                    break;
                case 7:
                    $errorMessage = '所属省市不能为空';
                    break;
                case 8:
                    $errorMessage = '所属等级不能为空';
                    break;
                case 9:
                    $errorMessage = '所属路线不能为空';
                    break;
                case 10:
                    $errorMessage = '医院描述不能为空';
                    break;
            }
            $res = array('sta'=>false,'errorMessage'=>$errorMessage);
        }
        return $res;
    }
//    function getHospitalBy
    static function getbreadNavByHosId($hosId,$artid)
    {
        $sql = <<<str
SELECT a.hos_id,a.hos_name,b.pro_name,b.pro_pinyin,b.pro_id,c.city_id,c.city_name,c.city_pinyin
FROM
hospital_hospital as a
JOIN
hospital_province as b
ON
(a.pro_id=b.pro_id)
JOIN
hospital_city as c
ON
(a.city_id=c.city_id)
where
a.hos_id = {$hosId}
str;
        $breadNav = M()->query($sql);
        $breadNavArr = array();
        array_push($breadNavArr,array('name'=>'全国','url'=>compareUrl()));
        array_push($breadNavArr,array('name'=>$breadNav[0]['pro_name'],'url'=>compareUrl($breadNav[0]['pro_pinyin'])));
        if($breadNav[0]['pro_name'] != $breadNav[0]['city_name'])
        {
            array_push($breadNavArr,array('name'=>$breadNav[0]['city_name'],'url'=>compareUrl($breadNav[0]['pro_pinyin'],$breadNav[0]['city_pinyin'])));
        }
        array_push($breadNavArr,array('name'=>$breadNav[0]['hos_name'],'url'=>U('/hos'.$breadNav[0]['hos_id'],'','').'/'));
        if ($artid) {
            $art = M("art")->where(array('art_id'=>$artid))->find();
            array_push($breadNavArr,array('name'=>$art['art_title'],'url'=>U('/hos'.$breadNav[0]['hos_id'].'/art-'.$art['art_id'],'','').'/'));
        }
        return $breadNavArr;
    }
}